<template>
  <div class="container">
    <Breadcrumb :items="['menu.form', 'Task List']" />

    <a-card class="general-card" :title="$t('Task List')">
      <a-list>
        <a-list-item v-for="task in sortedTasks" :key="task.id">
          <a-list-item-meta
            :title="`ID: ${task.id}, File IDs: ${task.file_ids}, Create Time: ${task.creat_time}, Status: ${task.status}`"
          />
          <template #actions>
            <a-button @click="viewDetails(task)">Detail</a-button>
            <a-button @click="prepareDownload(task)">Download Report</a-button>
          </template>
        </a-list-item>
      </a-list>
    </a-card>
    <!-- Detail Modal -->
    <a-modal
      v-model:visible="detailModalVisible"
      title="Task Details"
      @ok="detailModalVisible = false"
      @cancel="detailModalVisible = false"
    >
      <p><strong>ID:</strong> {{ selectedTask.id }}</p>
      <p><strong>File IDs:</strong> {{ selectedTask.file_ids }}</p>
      <p><strong>Create Time:</strong> {{ selectedTask.creat_time }}</p>
      <p><strong>Status:</strong> {{ selectedTask.status }}</p>
      <p><strong>time_consuming:</strong> {{ selectedTask.time_consuming }}</p>
      <div
        ><strong>More details:</strong>
        <textarea
          v-model="selectedTask.parser_log"
          class="textarea-details"
        ></textarea>
      </div>
    </a-modal>
    <!-- Scenario Selection Modal -->
    <a-modal
      v-model:visible="scenarioModalVisible"
      title="Select Scenarios"
      @ok="confirmDownload"
      @cancel="scenarioModalVisible = false"
    >
      <a-checkbox-group
        v-model="selectedScenarios"
        :options="scenarioOptions"
      ></a-checkbox-group>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import axios from 'axios';
  // import { Breadcrumb, Card, List, ListItem, ListItemMeta, Button, Modal, CheckboxGroup, Checkbox } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import baseUrl from '../../../config';


  const tasks = ref([]);
  const selectedTask = ref({
    id: '',
    file_ids: [],
    creat_time: '',
    status: '',
    time_consuming: '',
    parser_log: '',
  });
  const detailModalVisible = ref(false);
  const scenarioModalVisible = ref(false);
  const selectedScenarios = ref([]);
  const scenarioOptions = ref([
    { label: 'Scenario 1', value: 1 },
    { label: 'Scenario 3', value: 3 },
  ]);
  const { loading, setLoading } = useLoading();

  const sortedTasks = computed(() => {
    return tasks.value.slice().sort((a, b) => b.id - a.id);
  });

  const fetchScenarios = async () => {
    try {
      const response = await axios.get(
        'http://101.35.43.81:8111/api/scenarios/',
        {
          headers: {
            'accept': 'application/json',
            'X-CSRFToken':
              'mC19j9JWP7X6VIDkPclBPuQVxbXGtzpwBAtYpmxreyLH3P8VawaddJeK39KvpzWV',
          },
        }
      );
      if (response.status === 200) {
        scenarioOptions.value = response.data.map((scenario) => ({
          label: scenario.name,
          value: scenario.id,
        }));
      }
      selectedScenarios.value = scenarioOptions.value.map(
        (option) => option.value
      ); // 将所有场景ID设置为选中状态
    } catch (error) {
      console.error('Error fetching scenarios:', error);
    }
  };

  const fetchTasks = async () => {
    setLoading(true);
    try {
      const response = await axios.get(
        'http://101.35.43.81:8111/api/file-task',
        {
          headers: {
            'accept': 'application/json',
            'X-CSRFToken':
              'mC19j9JWP7X6VIDkPclBPuQVxbXGtzpwBAtYpmxreyLH3P8VawaddJeK39KvpzWV',
          },
        }
      );
      if (response.status === 200) {
        tasks.value = response.data.results;
      }
    } catch (error) {
      console.error('Error fetching tasks:', error);
    } finally {
      fetchScenarios();
      setLoading(false);
    }
  };

  const viewDetails = (task) => {
    selectedTask.value = task;
    detailModalVisible.value = true;
  };

  const prepareDownload = (task) => {
    selectedTask.value = task;
    scenarioModalVisible.value = true;
  };

  const downloadReport = async () => {
    const url = `${baseUrl}/api/download-report`;
    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRFToken':
            'hVoNjwQSSGkaqVPvZqyE0sJFuP1QoAawPG0ukQyFlmF1ChVZGc46vXVg5eylmff8',
        },
        body: JSON.stringify({
          task_id: selectedTask.value.id,
          scenario_ids: selectedScenarios.value,
        }),
      });

      const blob = await response.blob();
      const downloadUrl = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = downloadUrl;
      a.download = `${selectedTask.value.id}_report.xlsx`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(downloadUrl);
    } catch (error) {
      console.error('Failed to download file:', error);
    }
  };

  const confirmDownload = async () => {
    scenarioModalVisible.value = false;
    await downloadReport();
  };

  onMounted(fetchTasks);
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 40px 20px;
    overflow: hidden;
  }
  .textarea-details {
    width: 100%; /* 充满容器的宽度 */
    height: 4 00px; /* 设置一个固定高度 */
    resize: none; /* 禁止用户调整大小 */
  }
</style>
